package com.wanban.adutils.db

import android.text.TextUtils
import androidx.room.TypeConverter
import com.wanban.adutils.db.bean.AdInfo
import org.json.JSONArray
import org.json.JSONObject

class AdInfoConverters {
    @TypeConverter
    fun stringToList(value: String?): ArrayList<AdInfo>? {
        return if (TextUtils.isEmpty(value)) {
            null
        } else {
            val result = ArrayList<AdInfo>()
            val jsonArray = JSONArray(value!!)
            for (index in 0 until jsonArray.length()) {
                val jsonObj = jsonArray.getJSONObject(index)
                val adInfo = AdInfo()
                adInfo.adId = jsonObj.optLong("adId")
                adInfo.ad_type = jsonObj.optInt("ad_type")
                adInfo.timeout = jsonObj.optInt("timeout")
                adInfo.interval = jsonObj.optInt("interval")
                adInfo.showTime = jsonObj.optLong("showTime")
                adInfo.isCache = jsonObj.optBoolean("isCache")
                adInfo.advertiser = jsonObj.optInt("advertiser")
                adInfo.ad_duration = jsonObj.optInt("ad_duration")
                adInfo.ad_position = jsonObj.optString("ad_position")
                result.add(adInfo)
            }
            result
        }

    }

    @TypeConverter
    fun listToString(list: ArrayList<AdInfo>?): String? {
        return if (list?.isNotEmpty() == true) {
            val jsonArray = JSONArray()
            for (adInfo in list) {
                val jsonObj = JSONObject()
                jsonObj.put("adId", adInfo.adId)
                jsonObj.put("ad_type", adInfo.ad_type)
                jsonObj.put("timeout", adInfo.timeout)
                jsonObj.put("interval", adInfo.interval)
                jsonObj.put("showTime", adInfo.showTime)
                jsonObj.put("isCache", adInfo.isCache)
                jsonObj.put("advertiser", adInfo.advertiser)
                jsonObj.put("ad_duration", adInfo.ad_duration)
                jsonObj.put("ad_position", adInfo.ad_position)
                jsonArray.put(jsonObj)
            }
            jsonArray.toString()
        } else {
            null
        }
    }
}